#ifdef VERTEX
uniform mat4 uProjMatrix;
uniform mat4 uViewMatrix;
uniform mat4 uModelMatrix;

layout(location = 0) in vec4 aPosition;
layout(location = 1) in vec2 aTexCoord;
layout(location = 2) in vec4 aNormal;
layout(location = 3) in vec4 aColor;

out vec3 vTexCoord;
out vec3 vUpDirection;

void main()
{
	vec4 position = uProjMatrix * uViewMatrix * aPosition;
	vTexCoord = aPosition.xyz;
	vUpDirection = vec3(uViewMatrix[0][1], uViewMatrix[1][1], uViewMatrix[2][1]);
	gl_Position = position.xyww;
}
#endif

#ifdef FRAGMENT
uniform samplerCube uTexture;
uniform float uIntensity;

in vec3 vTexCoord;
in vec3 vUpDirection;
out vec4 fragColor;

void main()
{
	const float PI = 3.14159265359;
	vec3 normal = normalize(vTexCoord);
	vec3 binormal = normalize(cross(normal, vUpDirection));
	vec3 tangent = normalize(cross(binormal, normal));

	vec3 irradiance = vec3(0.0);
	float sampleDelta = 0.025;
	int sampleCount = 0;
	for (float x = 0.0; x < 2.0 * PI; x += sampleDelta)
	{
		for (float y = 0.0; y < 0.5 * PI; y += sampleDelta)
		{
			vec3 sampleVec = vec3(sin(y) * cos(x), sin(y) * sin(x), cos(y));
			vec3 texCoord = sampleVec.x * tangent + sampleVec.y * binormal + sampleVec.z * normal;
			irradiance += texture(uTexture, texCoord).rgb * cos(y) * sin(y);
			sampleCount++;
		}
	}
	fragColor = vec4(irradiance * (PI / float(sampleCount)) * uIntensity, 1.0);
}
#endif